import {
  getStoresByStatus,
  getStoresByNameLike,
  getStoreClass,
  getUsers,
  putFacilitator,
} from '../../../services/api';

export default {
  namespace: 'facilitatorAudit',

  state: {
    data: {
      list: [],
      pagination: {},
    },
  },

  effects: {
    *fetch({ payload: currentPage }, { call, put }) {
      const response = yield call(getStoresByStatus, currentPage);
      const category = yield call(getStoreClass);
      const allUsers = yield call(getUsers, 'merchant', currentPage);
      yield put({
        type: 'save',
        payload: { response, category, allUsers },
      });
    },
    *audit({ payload, callback }, { call, put }) {
      const { id, status, currentIndex } = payload;
      yield call(putFacilitator, id, { status });
      yield put({
        type: 'delete',
        payload: currentIndex,
      });
      if (callback) callback();
    },
    *search({ payload }, { call, put }) {
      const response = yield call(getStoresByNameLike, payload);
      const category = yield call(getStoreClass);
      yield put({
        type: 'save',
        payload: { response, category },
      });
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        data: payload.response,
        category: payload.category.list,
        users: payload.allUsers.list,
      };
    },
    append(state, action) {
      const { list } = state.data;
      list.unshift(action.payload);
      const total = state.data.pagination.total + 1;
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
            total,
          },
        },
      };
    },
    delete(state, action) {
      const { list } = state.data;
      list.splice(action.payload, 1);
      const total = state.data.pagination.total - 1;
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
            total,
          },
        },
      };
    },
    replace(state, action) {
      const { list } = state.data;
      list.splice(action.payload.editableIndex, 1, action.payload.response);
      return {
        ...state,
        data: {
          list,
          pagination: {
            ...state.data.pagination,
          },
        },
      };
    },
  },
};
